<?php

/**
 * 登录页面
 * @author hfc
 * @since 2015-6-29
 */
namespace apps\admin\controllers;
if( !defined( 'APP_ROOT' ) ){ echo 'Direct Access Deny!'; return; }

use apps\admin\models\PriUsers;
use enums\DBEnums;
use libraries\Verify;
use Phalcon\Mvc\Controller;
use apps\admin\models\LogAdminLogin;
use helpers\TimeUtils;
use apps\admin\models\ImgAssets;
use enums\PriEnums;

class LoginController extends Controller
{
	use \apps\admin\libraries\TAdminAcl;
	private $retryCnt = 6;
	
    public function initialize()
    {
    }
    
    
    /**
     *  登录
     */
    public function indexAction()
    {
    	if( $this->session->get( 'userInfo' ) )
    	{
    		$this->response->redirect( 'index/index' );
    	}
    	
        $remember = $this->cookies->has( 'remember' );
        if( $remember ) //传递密码
        {
            $this->view->setVar( 'password', $this->cookies->get( 'remember')->getValue() );
            $this->view->setVar( 'remember', $remember );
        }

        if( !( $strNum = $this->session->get( 'sid' )))
        {
            $num = rand( 0, 10000000000 );

            $strNum = md5( $num );

            $this->session->set( 'sid' , $strNum );
        }

        $this->view->setVar( 'sid', $strNum );
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = 'ajax 请求登录页面' )	
     * @method( method = 'doLoginAction' )
     * @op( op = '' )		
    */
    public function doLoginAction()
    {
        $loginName = $this->request->getPost( 'loginname', 'trim' );
        $password = $this->request->getPost( 'password', 'trim' );
        $error = $this->dataCache->get( 'error_' . $loginName ); //判断是否锁定
        if( isset( $error[ 'status' ] ) && PriEnums::USER_STATE_LOCK == $error[ 'status' ] )
        {
            $ret[ 'state' ] = 1;
            $ret[ 'msg' ] = '账号已锁定，请两小时后再输入。';
            $ret[ 'key' ] = $this->security->getTokenKey();
            $ret[ 'token' ] = $this->security->getToken();
            echo json_encode( $ret );
            return false;
        }
        
        $where = array(
                'loginname=:loginname: and delsign=' . DBEnums::DELSIGN_NO, 
                'bind' => array(
                    'loginname' => "$loginName"
                ), 
                'columns' => 'id,role_id,status,pwd,name,loginname,nickname,email,birthdate,avatar'
        );
        
        $user = PriUsers::findFirst( $where );
        if( $user )
        {
            $user = $user->toArray();
            if( isset( $user[ 'pwd' ] ) && $user[ 'pwd' ] && $user  )
            {

                $secret = sha1( trim( $this->session->get( 'sid' )) . trim( $user[ 'pwd' ] ));

                if( $secret != $password )
                {
                    if( ! isset( $error[ 'cnt' ] ) )
                    {
                        $error[ 'cnt' ] = 1;
                    }
                    else 
                  	{
                        if( $error[ 'cnt' ] > $this->retryCnt ) //大于设定次数
                        {
                            $error[ 'status' ] = PriEnums::USER_STATE_LOCK;
                        }
                        $error[ 'cnt' ]++;
                    }
                    
                    $this->dataCache->save( 'error_' . $loginName, $error, 7200 );
                    $ret[ 'state' ] = 1;
                    //修改密码尝试错误次数提示信息
                 	if( $error[ 'cnt' ] < $this->retryCnt )
                    {
                        $ret[ 'msg' ] =  '已输入' . $error[ 'cnt' ] . '次，还有'. ( $this->retryCnt - $error[ 'cnt' ] ) .  '次机会';
                    }
                    else if( $error[ 'cnt' ] >= $this->retryCnt )
                    {
                        $ret[ 'msg' ] = '账号已锁定，请两小时后再输入。';
                    }
                    
                    $ret[ 'key' ] = $this->security->getTokenKey();
                    $ret[ 'token' ] = $this->security->getToken();
                    echo json_encode( $ret );
                    return;
                }
            }
            if( isset( $user[ 'status' ] ) )
            {
                if( PriEnums::USER_STATE_NORMAL == $user[ 'status' ] )
                {
                    $this->rememberPassword( $user[ 'pwd' ] ); //登录成功，记忆密码
                    unset( $user[ 'pwd' ] );
                    $this->_setMenus( $user );//把菜单保存到缓存中
                    
                    $ret[ 'state' ] = 0;
                    $ret[ 'msg' ] = '登录成功';
                    
                    $logLogin = new LogAdminLogin();
                    $logLogin->user_id = $user[ 'id' ];
                    $logLogin->last_login_ip = $_SERVER[ 'REMOTE_ADDR' ];
                    $logLogin->last_login_time = TimeUtils::getFullTime();
                    $logLogin->sid = $this->session->getId();
                    $logLogin->useragent = $_SERVER[ 'HTTP_USER_AGENT' ];
                    
                    $logLogin->save();
                    $this->dataCache->delete( 'error_' . $loginName );
                }
                else if( PriEnums::USER_STATE_LOCK == $user[ 'status' ] || ( isset( $error ) && $error[ 'status' ] ) )
                {
                    $ret[ 'state' ] = 3;
                    $ret[ 'msg' ] = '账号被锁定';
                }
                else if( PriEnums::USER_STATE_PAUSE == $user[ 'status' ] )
                {
                    $ret[ 'state' ] = 7;
                    $ret[ 'msg' ] = '账号暂停使用';
                }
                else if( PriEnums::USER_STATE_LOST == $user[ 'status' ] )
                {
                    $ret[ 'state' ] = 8;
                    $ret[ 'msg' ] = '账号忘记密码';
                }
            }
        }
        else
        {
            $ret[ 'state' ] = 2;
            $ret[ 'msg' ] = '账号不存在';
        }
        $ret[ 'key' ] = $this->security->getTokenKey();
        $ret[ 'token' ] = $this->security->getToken();
        echo json_encode( $ret );
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = '设置左边菜单' )	
     * @method( method = '_setMenus' )
     * @op( op = '' )		
    */
    private function _setMenus( $userInfo = null ) 
    {
    	//浏览器 + ip地址
		$strVerfiy =  trim( $_SERVER[ 'HTTP_USER_AGENT' ] ) . trim( $_SERVER[ 'REMOTE_ADDR' ] );
    	if( false == $userInfo )
            return false;
    	$userInfo[ 'session_verfiy' ] 			= $strVerfiy;
    	$userInfo[ 'admin_regenrator_time' ]	= $_SERVER[ 'REQUEST_TIME' ];
    	
//     	$img = new PriUsersAvatarPics();
    	
    	$imgAvatar = ImgAssets::findFirst($userInfo['avatar']);
    	
//     	$info = $img->getPicById( $userInfo[ 'id' ] , $userInfo['avatar'] );
        assert( $imgAvatar );
    	if( $imgAvatar )
    	{
            $fsCfg = $this->di['ueditorCfg']->fs;
    	    
        	$userInfo[ 'avatarSrc' ] = $fsCfg->paths->{$fsCfg->cur}->url . $imgAvatar->path_name;
    	}
    	else
    	{
    	    unset( $userInfo[ 'avatarSrc' ] );
    	}
    	
        $this->session->set( 'userInfo', $userInfo ); // 保存session
        
        //设置权限 菜单
        $this->setAcl( $userInfo[ 'role_id' ] ); //设置权限
    }
  
    /**
     * 退出登录
     */
    public function logoutAction()
    {
        $userInfo = $this->session->get( 'userInfo' );
        $this->session->remove( 'userInfo' );
        $this->session->destroy();
        $this->response->redirect( 'admin/login/index' );
    }
    
    /**
     * 输出验证码
     */
    public function verifyAction()
    {
        $verify = new Verify( $this->di, array( 'imageH' => 40, 'imageW' => 140, 'fontSize' => 20, 'length' => 4 ));
        $verify->entry( 'code' );
    }
    
    /**
     * 记忆密码
     */
    private function rememberPassword(  $password = '' )
    {
        $remember = $this->request->getPost( 'remember', 'int' );
        
        if( $remember )
        {
            $this->cookies->set( 'remember', $password, time() + 15 * 86400 ); //记忆15天
        }
        else
        {
            $remember = $this->cookies->has( 'remember' );
            if( $remember ) //如果存在就删除
            {
                $this->cookies->get( 'remember' )->delete( 'remember' );
            }
        }
    }
    
    /**
     * 验证验证码
     */
    private function checkCode()
    {
        $code = $this->request->getPost( 'code', 'trim' );
        $verify = new Verify( $this->di );

        if( ! $verify->check( $code, 'code') )
        {
            $ret['status'] = 6;
            $ret['msg'] = '验证码错误';
            $ret[ 'key' ] = $this->security->getTokenKey();
            $ret[ 'token' ] = $this->security->getToken();
            echo ( json_encode( $ret ) );
            return false;
        }
        return true;
    }
    
}
